<?php
/**
 * @link https://www.kancloud.cn/cleverstone/ymb2
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\models;

/**
 * 管理组服务类
 * @author cleverstone
 * @since ym2.0
 */
class SystemGroupService
{
    /**
     * 获取所有管理组名称列
     * @return array
     */
    public static function getAllGroupColumns()
    {
        $groupColumns = SystemGroup::query(['name'])->indexBy('id')->column();
        $groupColumns[Admin::ADMIN_GROUP] = '拥有者';

        return $groupColumns;
    }

    /**
     * 获取管理组名
     * @param int $id 管理组ID
     * @return string
     */
    public static function getNameById($id)
    {
        if ($id == Admin::ADMIN_GROUP) {
            return '拥有者';
        }

        $data = SystemGroup::query(['name'])->where(['id' => $id])->one();
        if (empty($data)) {
            return '-';
        }

        return $data['name'];
    }

    /**
     * 获取树形数据
     * @param array $filterWhere 筛选条件
     * @param boolean $markDisabled 是否标记禁用项
     * @return array
     */
    public static function tree($filterWhere = [], $markDisabled = false)
    {
        $query = SystemGroup::query();
        if (!empty($filterWhere)) {
            $query->andFilterWhere($filterWhere);
        }

        $data = $query->orderBy(['id' => SORT_DESC])->all();
        return self::treeRecursive($data, 0, $markDisabled);
    }

    /**
     * 递归标记和格式化数据
     * @param array $data 组数据
     * @param int $pid PID
     * @param boolean $markDisabled 是否标记禁用项
     * @return array
     */
    protected static function treeRecursive(array $data, $pid = 0, $markDisabled = false)
    {
        $result = [];
        foreach ($data as $i => $item) {
            if ($item['pid'] == $pid) {
                unset($data[$i]);
                $item['children'] = self::treeRecursive($data, $item['id'], $markDisabled);
                if ($markDisabled) {
                    $item['disabled'] = !$item['status'] || !$item['assigned'];
                }

                $result[] = $item;
            }
        }

        return $result;
    }
}